package cn.itcast.gateway.filter;

import org.apache.http.HttpStatus;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

@Component
public class LoginFiler implements GlobalFilter, Order {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String log = request.getQueryParams().getFirst("log");
        if("admin".equals(log)){
            return chain.filter(exchange);
        }else {
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(HttpStatus.SC_UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int value() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }
}
